package com.test.nio.demo02;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;


public class ServerSocketChannelDemo {

	void start() throws IOException{
		ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
		serverSocketChannel.socket().bind(new InetSocketAddress(8999));
		serverSocketChannel.configureBlocking(false);
		
		while(true){
			SocketChannel socketChannel = serverSocketChannel.accept();
			if(socketChannel!=null){
				ByteBuffer buff = ByteBuffer.allocate(48);
				int size = socketChannel.read(buff);
				while(size>0){
					buff.flip();
					Charset charset = Charset.forName("UTF-8");
					System.out.print(charset.decode(buff).toString());
					buff.clear();
					size = socketChannel.read(buff);
				}
				socketChannel.close();
			}
		}
	}
	
	public static void main(String[] args) throws IOException {
		new ServerSocketChannelDemo().start();
	}
}
